<?php
/**
 * 模型基类
 */

namespace app\common\model;

use think\Db;
use think\facade\Session;
use think\Model;

class BaseModel extends Model
{

    /**
     * 获取登录KEY
     * @return mixed
     */
    public function getSessionKey(){
        return Session::get('session_key');
    }

    /**
     * 获取登录信息
     * @param string $field
     * @return mixed
     */
    public function getLoginInfo($field=''){
        $loginInfo = Session::get($this->getSessionKey());
        if(empty($field)) return $loginInfo;
        return $loginInfo[$field];
    }
    /**
     * 通用搜索器
     * filter: {"createtime":"2018-10-26 00:00:00 - 2018-10-26 23:59:59","admin_id":1}
     * op: {"createtime":"BETWEEN","admin_id":"="}
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchCommonAttr($query, $value, $data)
    {
        //字段
        if (isset($data['field'])) {
            $query->field($data['field']);
        }
        //排序
        if (isset($data['sort'])) {
            $query->order($data['sort']);
        }
        if(isset($data['append'])){
            $query->append(explode(',',$data['append']));
        }
        if(isset($data['hidden'])){
            $query->hidden(explode(',',$data['hidden']));
        }
        $filter=$value[0];
        $op=$value[1];
        $where = [];
        //按字段搜索
        $searchKey = \think\facade\Request::param('searchKey');
        $searchValue = \think\facade\Request::param('searchValue');
        if(!empty($searchKey) && !empty($searchValue)){
            $query->where($searchKey,'like',"%{$searchValue}%");
        }
        foreach ($filter as $k => $v) {
            $oldK=$k;
            $v = !is_array($v) ? trim($v) : $v;
            if(strlen($v)==0 || strlen($k)==0) continue;
            $opStr = strtolower(isset($op[$oldK]) ? $op[$oldK] : '='); //检索符号
            switch ($opStr) {
                case '=':
                case '!=':
                    $query->where($k,$opStr, (string)$v);
                    break;
                case 'like':
                case 'not like':
                    $query->where($k,$opStr, "%{$v}%");
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $v = ceil($v) == $v ? intval($v) : floatval($v);
                    $query->where($k,$opStr, $v);
                    break;
                case 'find_in_set':
                    $str = "FIND_IN_SET('{$v}',`{$k}`)";
                    $query->where('','EXP', Db::raw($str));
                    break;
                case 'in':
                case 'not in':
                case 'between':
                case 'not between':
                    $v = str_replace(' - ',',',$v);
                    $query->where($k,$opStr,$v);
                    break;
                case 'null':
                case 'not null':
                    $where[] = [$k, $opStr];
                    break;
                case '> time':
                case '>= time':
                case '< time':
                case '<= time':
                    $query->where($k,$opStr,$v);
                    break;
                case 'between time':
                    $v = str_replace(' - ',',',$v);
                    $query->where($k,$opStr,$v);
                    break;
                case 'today':
                case 'yesterday':
                case 'week':
                case 'last week':
                case 'month':
                case 'last month':
                case 'year':
                case 'last year':
                case 'customer time':
                    $opStr = $opStr=='customer time' ? $v : $opStr;
                    $query->whereTime($k, $opStr);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 查找单条记录
     * @param $map
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($map){
        $info = $this->where($map)->find();
        return $info;
    }
    /**
     * 添加数据
     * @param $data
     */
    public function addData($data){
        $info = self::create($data,true);
        return $info;
    }

    /**
     * 更新数据
     * @param $data
     */
    public function editData($data){
        $info = self::update($data,[],true);
        return $info;
    }

    /**
     * 删除数据
     * @param $data
     */
    public function delData($data){
        if(is_numeric($data)){
            $this->where('id','=',$data)->delete();
        }else{
            $this->where('id','in',$data)->delete();
        }
    }
    /**
     * 批量更新数据
     * @param $ids 逗号隔开的主键值，例：1,2,3,4,5
     * @param $params 修改的数据，例：status:1,is_boss:0
     * @return bool
     * @throws \Exception
     */
    public function multi($ids,$params){
        try{
            parse_str(str_replace([':',','],['=','&'],$params),$values);
            $this->where('id','in',$ids)->update($values);
        }catch (\Exception $e){
            exception($e->getMessage(),$e->getCode());
        }
        return true;
    }

    /**
     * 富文本数据处理
     * @param $value
     * @return string
     */
    protected function formatContent($value)
    {
        return stripslashes(htmlspecialchars_decode($value));
    }
    /**
     * 格式化图集
     */
    public function formatMultiImageDesc($pics)
    {
        if (empty($pics)) return '';
        $dataList = [];
        foreach ($pics['url'] as $k => $v) {
            $dataList[] = [
                'url' => $v,
                'title' => empty($pics['title'][$k]) ? '' : $pics['title'][$k],
                'remark' => empty($pics['remark'][$k]) ? '' : $pics['remark'][$k],
                'href' => empty($pics['href'][$k]) ? '' : htmlspecialchars_decode($pics['href'][$k]),
            ];
        }
        return json_encode($dataList,JSON_UNESCAPED_UNICODE);
    }

}